# frozen_string_literal: true

module Gitlab
  module BackgroundMigration
    # This migration fixes existing `vulnerability_reads` records which did not have `has_issues`
    # correctly set at the time of creation.
    class FixVulnerabilityReadsHasIssues < BatchedMigrationJob
      operation_name :fix_has_issues
      feature_category :vulnerability_management

      # rubocop:disable Style/Documentation
      class VulnerabilityRead < ::ApplicationRecord
        self.table_name = 'vulnerability_reads'

        scope :with_vulnerability_ids, ->(ids) { where(vulnerability_id: ids) }
        scope :without_issues, -> { where(has_issues: false) }
      end
      # rubocop:enable Style/Documentation

      def perform
        each_sub_batch do |sub_batch|
          vulnerability_reads_with_issue_links(sub_batch).update_all('has_issues = true')
        end
      end

      private

      def vulnerability_reads_with_issue_links(sub_batch)
        VulnerabilityRead.with_vulnerability_ids(sub_batch.select(:vulnerability_id)).without_issues
      end
    end
  end
end
